//
//  PopAnimatiedController.swift
//  BBAnimatedTransitioningDemo
//
//  Created by YouMao on 2022/4/27.
//

import UIKit
import BBAnimatedTransitioning

class PresentAnimatiedController: UIViewController {

    let animator: BBTransitiontingAnimator = BBTransitiontingAnimator()
    
    let interaction = UIPercentDrivenInteractiveTransition()
    
    let scrollView: UIScrollView = UIScrollView()
        
    init() {
        super.init(nibName: nil, bundle: nil)
        self.title = "Present"
        modalPresentationStyle = .custom
        transitioningDelegate = animator
        animator.outInteraction = interaction
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .green
        
        let label = UILabel(frame: CGRect(x: 0, y: 300, width: view.frame.size.width, height: 40))
        label.textAlignment = .center
        label.text = "下滑退出"
        view.addSubview(label)
        
        let pan = UIPanGestureRecognizer(target: self, action: #selector(pan(_:)))
        view.addGestureRecognizer(pan)
    }
    
    deinit {
        print(self)
    }
}

extension PresentAnimatiedController {
    @objc func pan(_ gesture: UIPanGestureRecognizer) {
        if gesture.state == .began {
            self.dismiss(animated: true) {
                
            }
        } else if gesture.state == .changed {
            let offset = gesture.translation(in: view)
            if offset.y > 0 &&  offset.y < 300 {
                interaction.update(offset.y / 300.0)
            }
        } else if gesture.state == .cancelled {
            interaction.cancel()
        } else if gesture.state == .ended {
            if interaction.percentComplete > 0.4 {
                interaction.finish()
            } else {
                interaction.cancel()
            }
        }
    }
}
